#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Description:风险系统的计算
Author:yyzhou，GY
Updated at 2019.07.01
"""

import json
import os
import random
import time
import MySQLdb


# 判断消息类别
def msg(d):
    if d['msg'] == 'report':
        return 0
    else:
        return 1

# 判断是否为威胁攻击信息
def Layer(d):
    if d['layer'] == 'attack':
        return 0
    elif d['layer'] == 'performance':
        return 1
    else:
        return 2


# 性能信息处理函数
def function_performance(d):
    if d['layer_info']['host'] == 'S1':
        S1_CPU_rate = d['layer_info']['CPU_uti']
        S1_RAM_rate = d['layer_info']['RAM_uti']
        # 以下为新增
        S1_In_speed = d['layer_info']['In_speed']
        S1_Out_speed = d['layer_info']['Out_speed']
        # 下面要把上下行速率也加入数据库
        cur.execute("insert into presentation_s1_integrated_state(S1_CPU_rate, S1_RAM_rate, S1_In_speed, S1_Out_speed) values(%s,%s,%s,%s)",
           [S1_CPU_rate, S1_RAM_rate, S1_In_speed, S1_Out_speed])
    if d['layer_info']['host'] == 'S2':
        S2_CPU_rate = d['layer_info']['CPU_uti']
        S2_RAM_rate = d['layer_info']['RAM_uti']
        # 以下为新增
        S2_In_speed = d['layer_info']['In_speed']
        S2_Out_speed = d['layer_info']['Out_speed']
        # 下面要把上下行速率也加入数据库
        cur.execute("insert into presentation_s2_integrated_state(S2_CPU_rate, S2_RAM_rate, S2_In_speed, S2_Out_speed) values(%s,%s,%s,%s)",
           [S2_CPU_rate, S2_RAM_rate, S2_In_speed, S2_Out_speed])
    if d['layer_info']['host'] == 'C1':
        C_CPU_rate = d['layer_info']['CPU_uti']
        C_RAM_rate = d['layer_info']['RAM_uti']
        cur.execute(
            "insert into presentation_c_integrated_state(C_CPU_rate, C_RAM_rate) values(%s,%s)",
            [C_CPU_rate, C_RAM_rate])


if __name__ == '__main__':
    while 1:
        # 连接数据库
        conn = MySQLdb.connect(
                    host='localhost',
                    port=3306,
                    user='root',
                    passwd='cnv6201',
                    db='PRESENTATION',
                    charset='utf8',
                )
        cur = conn.cursor()
        cur.execute("delete from presentation_s1_integrated_state")
        cur.execute("delete from presentation_s2_integrated_state")
        cur.execute("delete from presentation_c_integrated_state")

        
        path = os.getcwd() + '/JsonPerformanceReport/'  # 获取攻击威胁目录
        dirs = os.listdir(path)
        for i in dirs:                                  # 循环读取路径下的文件
            with open(path + i, 'r', encoding='UTF-8') as f:
                data = json.load(f)
                if msg(data) == 0:                      # 判断消息类型是否为上报
                    if Layer(data) == 1:
                        function_performance(data)
                else:
                    print("数据不是上报类型，不归我管！")

        cur.close()
        conn.commit()
        conn.close()

        time.sleep(10)
